package com.glsc.ngateway.opmanage.aspect;

//import com.glsc.ngateway.common.api.platform.dto.it.command.BaseEntityDto;
import com.glsc.ngateway.common.api.common.dto.BaseEntityDto;
import com.glsc.ngateway.opmanage.exception.PlatformException;
import org.apache.logging.log4j.util.Strings;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 为参数添加操作人员
 *
 * @author xuchang
 */
public class OperatorArgumentResolver implements HandlerMethodArgumentResolver {

    HandlerMethodArgumentResolver handlerMethodArgumentResolver;

    public OperatorArgumentResolver(HandlerMethodArgumentResolver handlerMethodArgumentResolver) {
        this.handlerMethodArgumentResolver = handlerMethodArgumentResolver;
    }


    /**
     * 必须是@RequestBody且extends BaseEntityDto 的参数类才能被代理
     *
     * @param parameter the method parameter to check
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(RequestBody.class) && BaseEntityDto.class.isAssignableFrom(parameter.getParameterType());
    }

    /**
     * 进行代理
     *
     * @param parameter     the method parameter to resolve. This parameter must
     *                      have previously been passed to {@link #supportsParameter} which must
     *                      have returned {@code true}.
     * @param mavContainer  the ModelAndViewContainer for the current request
     * @param webRequest    the current request
     * @param binderFactory a factory for creating {@link WebDataBinder} instances
     * @return
     * @throws Exception
     */
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String token = ((ServletWebRequest) webRequest).getRequest().getHeader("token");
        //有微服务调用情况不传token，就不需要加载操作人员信息
        if (Strings.isNotBlank(token) && !"null".equals(token)) {
            //根据token解析出，登录用户account
            String account = JwtHelper.parseToken(token);
            if (Strings.isBlank(account)) {
                throw PlatformException.error("无权限，token不合法", true, false);
            }
            BaseEntityDto param = (BaseEntityDto) handlerMethodArgumentResolver.resolveArgument(parameter, mavContainer, webRequest, binderFactory);
            param.setCreateAccount(account);
            param.setUpdateAccount(account);
            return param;
        }
        return parameter;
    }
}
